- instanceOf原理,手动实现function isInstanceOf(child,parent)
- instanceof原理:查询parent的prototype是否在child的原型链上,所以在查找过程中,instanceof会遍历child的原型链,直到找到或查找失败。
判断一个实例是否属于某种类型:
let person = function(){};
let person1 = new person();
person1 instanceof person; //true
- 手动实现isInstanceOf
function isInstanceOf(child,parent){
let parentProto = parent.prototype;
child = child.__proto__;
while(1){
if(child === null){
return false;
}
if(child === parentProto){
return true;
}
child = child.__proto__;
}
}
function isInstanceOf(child,parent){
let parentProto = parent.prototype;
child = child.__proto__;
while(child){
if(child === parentProto){
return true;
}
child = child.__proto__;
}
return false;
}